package com.xxin.controller.sys;

import com.github.pagehelper.PageInfo;
import com.xxin.exceptions.BusinessException;
import com.xxin.pojo.entity.SysUsers;
import com.xxin.pojo.vo.DoctorVO;
import com.xxin.pojo.vo.SysUsersVO;
import com.xxin.resp.Result;
import com.xxin.service.SysUsersService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * @author 小欣
 * @version 1.0
 * @since 1.8
 */
@Controller
@RequestMapping("/api/users")
public class SysUsersController {
	
	@Resource
	private SysUsersService sysUsersService;
	
	private final Logger log = LogManager.getLogger(SysUsersController.class);
	@Value("${upload.address}")
	private String uploadPath;
	
	@GetMapping("/showImg")
	public ResponseEntity<byte[]> showImg(@RequestParam("userId") Long userId,HttpServletRequest request) throws IOException {
		String realPath = request.getServletContext().getRealPath(uploadPath);
		log.info("绝对路径:{}", realPath);
		log.info("查询图片接口:用户编号:{}",userId);
		String headUrl = Optional.ofNullable(sysUsersService.showImg(userId)).orElse("user.png");
		File file = new File(realPath + "\\" +   headUrl);
		// 创建响应头对象
		HttpHeaders headers = new HttpHeaders();
		// 设置响应内容类型
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		// 设置下载文件的名称
		headers.setContentDispositionFormData("attachment", file.getName());
		// 下载文件
		ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(Files.readAllBytes(file.toPath()), headers, HttpStatus.OK);
		return entity;
	}
	
	
	
	
	
	@RequestMapping("/list")
	public String userList(Model model,@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum){
		PageInfo<SysUsersVO> list = sysUsersService.pageQuery(pageNum);
		model.addAttribute("pages",list);
		return "userList";
	}
	
	@GetMapping("/addUser")
	public String addUser(){
		return "userAdd";
	}
	
	
	@GetMapping("/accountExist.json")
	@ResponseBody
	public Result accountExists(@RequestParam("account") String account){
		//TODO 判断用户是否存在
		sysUsersService.accountExists(account);
		return Result.success();
	}
	
	@PostMapping(value = "/addUser" ,consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
	@Transactional
	public String addUser(SysUsers sysUsers,@RequestPart("userImg") MultipartFile userImg,HttpServletRequest request) throws IOException {
		//获取文件的类型
		String fileType = Optional.of(userImg.getOriginalFilename().split("\\.")).map(farr -> farr[farr.length - 1]).orElseGet(() -> "");
		//以UUID作为文件名
		String fileName = UUID.randomUUID() + "." + fileType;
		sysUsers.setHeadUrl(fileName);
		log.info("新增用户信息:{}",sysUsers);
		// ... 其他属性
		try {
			sysUsersService.addUser(sysUsers,userImg);
		} catch (BusinessException e) {
			request.setAttribute("fileUploadError", e.getMessage());
			return "userAdd";
		}
		// 处理文件和其他逻辑
		InputStream is = userImg.getInputStream();
		File file = new File(request.getServletContext().getRealPath(uploadPath) + fileName);
		if(!file.exists()){
			file.createNewFile();
		}
		byte[] bytes = new byte[1024 * 100];
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
		int readCount;
		while((readCount = is.read(bytes)) != -1){
			bos.write(bytes,0,readCount);
		}
		bos.flush();
		is.close();
		bos.close();
		
		// 返回视图或其他逻辑
		return "redirect:/api/users/list";
	}
	
	@PostMapping("/getDoctorList.json")
	@ResponseBody
	public Result<List<DoctorVO>> getDoctorList(@RequestParam(value = "departmentId",required = false) Long departmentId){
		List<DoctorVO> doctorVOS = sysUsersService.getDoctorList(departmentId);
		return Result.success(doctorVOS);
	}
}
